<template>
  <div :class="{ 'has-logo': showLogo }" style="height: 100%; background-color: rgb(0, 21, 41)">
    <logo v-if="showLogo" :collapse="isCollapse" />
    <el-scrollbar
      wrap-class="scrollbar-wrapper"
      style="height: calc(100% - 102px); background-color: #006fff; scroll: no"
    >
      <el-menu
        v-if="!menuEdit"
        :default-active="activeMenu"
        :collapse="isCollapse"
        :background-color="variables.menuBg"
        :text-color="variables.menuText"
        :unique-opened="true"
        :active-text-color="variables.menuActiveText"
        :collapse-transition="false"
        mode="vertical"
        style="width: 100%; border: none"
      >
        <sidebar-item
          v-for="route in customRoutes"
          :key="route.path"
          :item="route"
          :base-path="route.path"
          class="sidebar_item"
        />
      </el-menu>
      <div v-else>
        <div class="head_home">
          <svg-icon icon-class="home" style="margin-right: 10px"></svg-icon>
          <span>首页</span>
        </div>
        <div v-for="route in editMenus" :key="route.path">
          <template v-if="route.path != '/dashboard/analysis'">
            <div class="edit_item">
              <el-checkbox v-model="route.show">{{ route.title }}</el-checkbox>
            </div>
          </template>
        </div>
      </div>
    </el-scrollbar>
    <div class="bottom-menu" style>
      <el-popover placement="right-end" width="400" trigger="hover" v-model="visible" popper-class="custom_popper">
        <div class="system_set_view">
          <div class="popper_title">系统设置</div>
          <div class="item_list">
            <div class="item_title" @click="routeClick(item)" v-for="(item, index) in routeList" :key="index">
              {{ item.title }}
            </div>
          </div>
        </div>
        <div slot="reference" class="userinfo" style="cursor: pointer">
          <svg-icon icon-class="setting" ref="guide5"></svg-icon>
        </div>
      </el-popover>
      <div v-if="menuEdit" @click="saveMenuEdit" class="save_menu">完成</div>
      <!-- @click="toOperateLog" -->
      <div v-else>
        <!-- <div v-show="showSet" style="position: absolute; text-align: center; bottom: 45px; right: 15px">导航设置</div>
        <svg-icon
          icon-class="b4"
          ref="guide6"
          @click="startEdit"
          style="margin-right: 30px; cursor: pointer"
          @mouseover="showSet = true"
          @mouseleave="showSet = false"
        ></svg-icon> -->
        <el-tooltip class="item" effect="dark" content="导航设置" placement="top">
          <svg-icon
          icon-class="b4"
          ref="guide6"
          @click="startEdit"
          style="margin-right: 30px; cursor: pointer"
        ></svg-icon>
        </el-tooltip>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Logo from './Logo'
import SidebarItem from './SidebarItem'
import Item from './Item'
import variables from '@/styles/variables.scss'
import Vue from 'vue'
import { USER_INFO, ACCOUNT_BOOK } from '@/store/mutation-types'
import { getAction, postAction, putAction } from '@/api/manage'

export default {
  components: { SidebarItem, Logo, Item },
  props: {
    routes: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    '$store.getters.openAccountValue'(val) {
      this.openAccount = val
      if (val !== 3) {
        // 需要延迟打开开账操作页面,等待先关闭页面
        setTimeout(() => {
          this.toSystemConfiguration()
        }, 100)
      }
    },
  },
  data() {
    return {
      baseVersion: true,
      logo: 'https://wpimg.wallstcn.com/69a1c46c-eb1c-4b46-8bd4-e9e686ef5251.png',
      visible: false,
      menuEdit: false,
      editMenus: [],
      isLeader: false,
      customRoutes: [],
      updateId: '',
      routeListData: [
        {
          title: '系统配置',
          path: '/setting/setSystem/setSystem',
        },
        {
          title: '权限设置',
          path: '/setting/authoritySet/authority',
        },
        {
          title: '账套管理',
          path: '/setting/ManagementZT/ManagementZT',
        },
        // {
        //   title: '新增账套',
        //   path: '/setting/ManagementZT/redactMessage/index',
        // },
        // {
        //   title: '单据编号规则设置',
        //   path: '',
        // },
        {
          title: '价格优先级设置',
          path: '/setting/pricePriority/index',
        },
        {
          title: '系统重置',
          path: '/setting/systemReset/index',
        },
        {
          title: '系统恢复',
          path: '/setting/dataReturn/index',
        },
        {
          title: '操作日志',
          path: '/home/operationLog',
        },
        {
          title: '开账操作',
          path: '/business/SystemConfiguration',
        },
      ],
      baseVersionPages: [
        '/dashboard/analysis', //首页
        '/sale', //销售管理
        '/baseInfomation/material/transactionCompanyInfo', //客户管理
        '/reportStatistics', //报表统计
        '/baseInfomation', //基本信息
        '/shopManage', //门店管理
      ],
      openAccount: -1,
      // 显示导航设置
      showSet: false,
    }
  },
  created() {
    console.log(this.routes)
    this.getIsLeader()
    this.getOpenAccountFlag()
  },
  mounted() {
    this.getOpenAccountFlag()
    this.getIsLeader()
    console.log('sidebar  mounted')
    var that = this
    this.$EventBus.$on('getGuideItem', function (res) {
      if (res == 5) {
        let rect = that.$refs.guide5.$el.getBoundingClientRect()
        let params = {
          rect,
          step: 5,
        }
        this.$EventBus.$emit('showNoviceGuide', params)
      } else if (res == 6) {
        let rect = that.$refs.guide6.$el.getBoundingClientRect()
        let params = {
          rect,
          step: 6,
        }
        this.$EventBus.$emit('showNoviceGuide', params)
      }
    })
    this.$EventBus.$on('changeAccountBook', function (res) {
      that.menuEdit = false
      that.editMenus = []
      that.getIsLeader()
    })
  },
  beforeDestroy() {
    console.log('sidebar  beforeDestroy')
    this.$EventBus.$off('getGuideItem')
    this.$EventBus.$off('changeAccountBook')
  },
  computed: {
    ...mapGetters(['sidebar']),
    activeMenu() {
      const route = this.$route
      const { meta, path } = route
      // if set path, the sidebar will highlight the path you set
      if (meta.activeMenu) {
        return meta.activeMenu
      }
      return path
    },
    showLogo() {
      return true //this.$store.state.settings.sidebarLogo
    },
    variables() {
      return variables
    },
    isCollapse() {
      return false //!this.sidebar.opened
    },
    isOpenAccount() {
      return this.openAccount === 3
    },
    routeList() {
      return this.routeListData.filter(item => {
        if (this.baseVersion && item.title === '权限设置') {
          return false
        }
        return true
      })
    },
  },
  methods: {
    routeClick(item) {
      console.log(item)
      
      // 账套过期不允许进入其他页面
      if (Vue.ls.get('account-no-money')) {
        return this.$elMessage.warning('续费未完成不能操作!')
      }
      // 必用版且已开账不允许进入开账操作页面
      if (this.baseVersion && this.isOpenAccount && item.path === '/business/SystemConfiguration') {
        return this.$elMessage.warning('已经开账,无需操作!')
      }
      if (!this.isOpenAccount && item.path != '/setting/dataReturn/index') {
        return this.$elMessage.warning('未开账不能操作!')
      }
      // 除了账套管理和操作日志，其他页面只有管理员可以进入
      if (item.path != '/home/operationLog' && item.path != '/setting/ManagementZT/ManagementZT' && !this.isLeader) {
        return this.$elMessage.warning('没有权限!')
      }

      console.log(item.path)
      this.visible = false
      this.$router.push(
        {
          path: item.path,
        },
        () => {},
        () => {}
      )
    },
    toOperateLog() {
      if (this.$route.path != '/home/operationLog') {
        this.$router.push('/home/operationLog')
      }
    },
    saveMenuEdit() {
      this.menuEdit = false
      this.addCustomRouters()
      let paths = []
      for (let i = 0; i < this.editMenus.length; i++) {
        const element = this.editMenus[i]
        paths.push(element.path)
      }

      let temp = []
      for (let i = 0; i < this.routes.length; i++) {
        const item = JSON.parse(JSON.stringify(this.routes[i]))
        if (paths.includes(item.path)) {
          item.hidden = this.getCustomLimit(item)
        }
        temp.push(item)
      }
      this.customRoutes = temp
      this.getCustomRoutesByVersion()
    },
    startEdit() {
      // 账套过期不允许进入页面
      if (Vue.ls.get('account-no-money')) {
        return this.$elMessage.warning('续费未完成不能操作!')
      }
      if (!this.isOpenAccount) {
        return this.$elMessage.warning('未开账不能操作!')
      }
      if (!this.isLeader) {
        this.$message.warning('只有账套持有人才可以编辑！')
        return
      }
      if (!this.editMenus || this.editMenus.length == 0) {
        let list = []
        for (let index = 0; index < this.customRoutes.length; index++) {
          const route = this.customRoutes[index]
          if (!route.hidden || route.meta.title == '客户管理') {
            list.push({
              title: route.meta.title,
              path: route.path,
              show: true,
            })
          }
        }
        this.editMenus = list
      }

      this.menuEdit = true
    },
    getCustomLimit(item) {
      for (let index = 0; index < this.editMenus.length; index++) {
        const element = this.editMenus[index]
        if (item.path == element.path) {
          return !element.show
        }
      }
      return false
    },
    getRouterLimit(item) {
      for (let index = 0; index < this.routes.length; index++) {
        const element = this.routes[index]
         if (this.baseVersion && element.meta.title == '客户管理') {
          return false
        } else if (item.path == element.path) {
          return element.hidden
        }
      }
      return true
    },
    getCustomRouters() {
      let accountBook = Vue.ls.get(ACCOUNT_BOOK)
      const bookId = accountBook && accountBook.id
      getAction('/fieldshowsetting/xghAccountBookFieldShowSetting/getByApiAndAccountBookId', {
        api: bookId,
      })
        .then(
          (res) => {
            if (res.success) {
              let result = res.result
              if (result) {
                this.updateId = result.id
                let fieldSetting = JSON.parse(result.fieldSetting)
                let rs = []
                let list = fieldSetting
                  .map((item) => {
                    let hidden = this.getRouterLimit(item)
                    if (!hidden) {
                      rs.push(item.path)
                      return item
                    }
                  })
                  .filter((item) => {
                    return item != undefined
                  })
                this.editMenus = list

                let temp = []
                for (let i = 0; i < this.routes.length; i++) {
                  const item = JSON.parse(JSON.stringify(this.routes[i]))
                  if (rs.includes(item.path)) {
                    item.hidden = this.getCustomLimit(item)
                  } else {
                    item.hidden = item.hidden || false
                  }
                  temp.push(item)
                }
                this.customRoutes = temp
              } else {
                this.updateId = ''
                this.customRoutes = JSON.parse(JSON.stringify(this.routes))
              }
            } else {
              this.updateId = ''
              this.customRoutes = JSON.parse(JSON.stringify(this.routes))
            }
            this.getCustomRoutesByVersion()
          },
          (error) => {
            this.updateId = ''
            this.customRoutes = JSON.parse(JSON.stringify(this.routes))
            this.getCustomRoutesByVersion()
          }
        )
        .catch((err) => {
          this.updateId = ''
          this.customRoutes = JSON.parse(JSON.stringify(this.routes))
          this.getCustomRoutesByVersion()
        })
    },
    getCustomRoutesByVersion() {
      if (this.baseVersion) { //基础版
        this.customRoutes = this.customRoutes.map(item => {
          if (this.baseVersionPages.includes(item.path)) {
            if (item.path == '/baseInfomation/material/transactionCompanyInfo') {
              let client = this.editMenus.find(el => el.path == item.path) //客户管理
              if (client) { //有自定义就用自定义的显示
                item.hidden = !client.show
              } else { //没有自定义就显示
                item.hidden = false
              }
            }
            return item
          }
        }).filter(el => el)
      } else {
        this.customRoutes = this.customRoutes.filter(item => !item.hidden)
      }
    },
    addCustomRouters() {
      let accountBook = Vue.ls.get(ACCOUNT_BOOK)
      const bookId = accountBook && accountBook.id
      let obj = {
        api: bookId,
        fieldSetting: JSON.stringify(this.editMenus),
      }
      if (this.updateId) {
        obj.id = this.updateId
        putAction('/fieldshowsetting/xghAccountBookFieldShowSetting/edit', obj).then((res) => {})
      } else {
        postAction('/fieldshowsetting/xghAccountBookFieldShowSetting/add', obj).then((res) => {
          if (res.code == 200) {
            this.updateId = res.result
          }
        })
      }
    },
    // 获取是否是leader
    async getIsLeader() {
      let accountBook = Vue.ls.get(ACCOUNT_BOOK)
      const bookId = accountBook && accountBook.id
      let vers = await getAction('/accountbookinfo/xghAccountBook/getVersion', {
        id: bookId,
      })
      if (vers.success) {
        let result = vers.result || '专业版'
        Vue.ls.set('accountVersion', result)
        //
        console.log('-------------getversion, ', result);
        
        this.baseVersion = result == '必用版'
      } 
      
      let userInfo = Vue.ls.get(USER_INFO)
      getAction('/accountbookusing/xghAccountBookUserUsing/getUserIsLeader', {
        userId: userInfo.id,
      }).then((res) => {
        this.isLeader = res.result == 1
        this.getCustomRouters()
      })
    },
    // 获取期初开账信息
    getOpenAccountFlag() {
      getAction('/openAccount/getOpenAccountType', {}).then((res) => {
        if (res.code === 200) {
          if (!res.result) {
            // 开单标志，res.result为null表示新账套
            this.$store.commit('SET_OPEN_ACCOUNT_VALUE', 0)
            this.openAccount = 0
            this.toSystemConfiguration()
          } else {
            this.openAccount = Number(res.result.value)
            this.$store.commit('SET_OPEN_ACCOUNT_VALUE', this.openAccount)
            // 开单标志，3表示已经开账，其他状态为开账中，需要跳转开账页面
            if (this.openAccount != 3) {
              this.toSystemConfiguration()
            } else {
              // 账套过期，跳转续费页面
              if (Vue.ls.get('account-no-money')) {
                console.log('账套过期，跳转续费页面')
                this.$router.push({ name: 'setting-buy-accountBookPay' }).catch((err) => {})
              }
            }
          }
        }
      })
    },
    // 跳转到开账操作页面
    toSystemConfiguration() {
      // 账套没有过期，跳转到开账页面，过期只能跳转续费页面
      if (!Vue.ls.get('account-no-money')) {
        this.$router.push({ name: 'business-SystemConfiguration' }).catch((err) => {})
      } else {
        this.$router.push({ name: 'setting-buy-accountBookPay' }).catch((err) => {})
      }
    },
  },
}
</script>
<style lang="less" >
.el-menu-item {
  display: flex !important;
  align-items: center !important;
}

.el-popover.custom_popper {
  background: rgb(18, 36, 68);
  border: none;
  padding: 0;
  border-radius: 5px;
}

.system_set_view {
  width: 100%;
  height: 260px;
  background: rgb(18, 36, 68);
  padding: 7px 37px;
}

.popper_title {
  width: 230px;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 500;
  line-height: 25px;
  color: #1b94fb;
  border-bottom: #1b94fb solid 1px;
  line-height: 40px;
  margin-bottom: 20px;
}

.item_title {
  height: 30px;
  width: 150px;
  color: #1b94fb;
  cursor: pointer;
}

.item_list {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 160px;

  & > div:hover {
    color: #fff;
  }
}

// .sidebar_item {
//   &.hover {
//     background-color: red;
//   }
// }
.save_menu {
  background: #1b94fb;
  font-size: 14px;
  font-family: PingFangSC-Regular;
  width: 62px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  cursor: pointer;
}
.edit_item {
  margin: 0;
  width: 100%;
  height: 50px;
  color: #fff;
  display: flex;
  font-size: 14px;
  padding-left: 30px;
  align-items: center;
}
.head_home {
  display: flex;
  align-items: center;
  padding-left: 30px;
  height: 50px;
  width: 100%;
  span {
    font-size: 14px;
    color: #fff;
    margin-left: 10px;
  }
}
</style>
